import React, { useState } from 'react';
import {
  Button,
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  Label,
  Text,
  Select,
  Badge,
  Spinner
} from 'packages/ui-shared/src/atoms';
import { AttendanceRecord, AttendanceStatus, saveAttendanceRecord } from '../mock/attendanceData';
import { mockGradeData } from '../mock/gradeData';
import { mockTeachers } from '../mock/teacherData';

interface AttendanceSignInProps {
  courseId: string;
  courseName: string;
  date: string;
  onClose: () => void;
  onSuccess: () => void;
}

const AttendanceSignIn: React.FC<AttendanceSignInProps> = ({
  courseId,
  courseName,
  date,
  onClose,
  onSuccess
}) => {
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [signInData, setSignInData] = useState<Record<string, AttendanceStatus>>({});
  
  // 初始化签到数据
  React.useEffect(() => {
    // 获取选修该课程的学生
    const enrolledStudents = mockGradeData
      .filter(grade => grade.courseName === courseName)
      .map(grade => ({ id: grade.studentId, name: grade.studentName }));
    
    // 初始化签到状态
    const initialData: Record<string, AttendanceStatus> = {};
    enrolledStudents.forEach(student => {
      initialData[student.id] = 'absent'; // 默认缺席
    });
    
    setSignInData(initialData);
  }, [courseName]);
  
  // 处理签到状态变更
  const handleStatusChange = (studentId: string, status: AttendanceStatus) => {
    setSignInData(prev => ({
      ...prev,
      [studentId]: status
    }));
  };
  
  // 提交签到记录
  const handleSubmit = async () => {
    setIsLoading(true);
    try {
      // 获取当前教师信息
      const currentTeacher = mockTeachers[0];
      
      // 获取选修该课程的学生
      const enrolledStudents = mockGradeData
        .filter(grade => grade.courseName === courseName)
        .map(grade => ({ id: grade.studentId, name: grade.studentName }));
      
      // 保存每个学生的签到记录
      for (const student of enrolledStudents) {
        const status = signInData[student.id] || 'absent';
        const record: AttendanceRecord = {
          id: `A${Date.now()}-${student.id}`,
          studentId: student.id,
          studentName: student.name,
          courseId: courseId,
          courseName: courseName,
          teacherId: currentTeacher.teacherId,
          teacherName: currentTeacher.name,
          scheduleId: `S00${courseId.slice(1)}`, // 简化的排课ID
          date: date,
          startTime: '08:00', // 简化处理
          endTime: '10:00', // 简化处理
          status: status,
          recordedBy: currentTeacher.name,
          recordTime: new Date().toISOString()
        };
        
        await saveAttendanceRecord(record);
      }
      
      onSuccess();
      alert('签到成功！');
    } catch (error) {
      console.error('签到失败:', error);
      alert('签到失败，请重试！');
    } finally {
      setIsLoading(false);
    }
  };
  
  // 获取状态对应的中文描述
  const getStatusText = (status: AttendanceStatus): string => {
    const statusMap: Record<AttendanceStatus, string> = {
      present: '出勤',
      absent: '缺勤',
      leave: '请假',
      late: '迟到'
    };
    return statusMap[status] || status;
  };
  
  return (
    <Dialog open={true} onOpenChange={onClose}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>课堂签到</DialogTitle>
        </DialogHeader>
        
        <div className="grid gap-4 py-4">
          <div>
            <Label>课程：{courseName}</Label>
          </div>
          <div>
            <Label>日期：{date}</Label>
          </div>
          
          {/* 学生签到列表 */}
          <div className="space-y-3 max-h-[400px] overflow-y-auto">
            {mockGradeData
              .filter(grade => grade.courseName === courseName)
              .map(grade => ({
                id: grade.studentId,
                name: grade.studentName
              }))
              .map(student => (
                <div key={student.id} className="flex items-center justify-between p-2 border rounded-md">
                  <div className="flex items-center">
                    <Text className="mr-2 font-medium">{student.name}</Text>
                    <Text className="text-sm text-gray-500">({student.id})</Text>
                  </div>
                  <Select
                    value={signInData[student.id] || 'absent'}
                    onChange={(e) => handleStatusChange(student.id, e.target.value as AttendanceStatus)}
                    className="w-32"
                  >
                    <option value="present">出勤</option>
                    <option value="absent">缺勤</option>
                    <option value="leave">请假</option>
                    <option value="late">迟到</option>
                  </Select>
                </div>
              ))
            }
          </div>
        </div>
        
        <DialogFooter>
          <Button onClick={onClose}>取消</Button>
          <Button 
            onClick={handleSubmit} 
            className="bg-green-500 hover:bg-green-600"
            disabled={isLoading}
          >
            {isLoading ? (
              <>
                <Spinner className="h-4 w-4 mr-2" />
                签到中...
              </>
            ) : '完成签到'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export default AttendanceSignIn;